#include "TcpServer.h"

int flag1 = 1;
extern char databuf[1024];
extern pthread_mutex_t mutex;  // 静态初始化

int main()
{
    //udp
    startUdpServer();
    
    //stm
    pthread_t tcpstm_thread;
    if (pthread_create(&tcpstm_thread, NULL, startTcpStmServer, NULL)) 
    {
        ERROR("pthread_create for TCPSTM");
        exit(-1);
    }
    pthread_detach(tcpstm_thread);



    //qt
    int sockfd = createSocket(QT_IP, (unsigned short)QT_PORT);
    mainLoop(sockfd);
    close(sockfd);
    sockfd = -1;
    

    return 0;
}



int createSocket(const char* ip, unsigned short port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd)
    {
        ERROR("socket");
        exit(-1);
    }

    int on = 1;
    if (-1 == (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))))
        ERROR("setsockopt");

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if (0 == inet_aton(ip, &server_addr.sin_addr))
    {
        ERROR("inet_aton");
        close(sockfd);
        sockfd = -1;
        exit(-1);
    }
    if (-1 == bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)))
    {
        ERROR("bind");
        close(sockfd);
        sockfd = -1;
        exit(-1);
    }

    if (-1 == listen(sockfd, 20))
    {
        ERROR("listen");
        exit(-1);
    }

    printf("QT_Server started on %s:%d\n", ip, port);
    return sockfd;

}

void mainLoop(int sockfd)
{
    struct sockaddr_in client_addr;
    unsigned int size = sizeof(client_addr);

    while(1)
    {
        int qt_fd = accept(sockfd, (struct sockaddr*)&client_addr, &size);
        if (-1 == qt_fd)
        {
            ERROR("accept");
            exit(-1);
        }
        //char* p = inet_ntoa(client_addr.sin_addr);
        //unsigned short port = ntohs(client_addr.sin_port);

        printf("QT_Client has been connected!\n");

        handleData(qt_fd);
    }

}

void handleData(int actfd)
{
    int* act_ptr = malloc(sizeof(int));
    *act_ptr = actfd;

    pthread_t send_thread;
    if (pthread_create(&send_thread, NULL, sendThreadFunc, act_ptr))
    {
        perror("pthread_create sendThreadFunc");
        close(actfd);
        free(act_ptr);
        return;
    }
    pthread_detach(send_thread);


    char buf[1024] = "";
    int ret;
    ret = recv(actfd,buf,sizeof(buf),0);
    if(0 == ret)
    {
        printf("QT_Client disconnected!\n");
    }
    if(-1 == ret)
    {
        ERROR("recv");
        close(actfd);
        actfd = -1;
        exit(-1);
    }
    
    FILE* fp = fopen(buf,"w");
    if(NULL == fp)
    {
        ERROR("fopen");
        exit(-1);
    }  

    
    while(1)
    {
        memset(buf,0,sizeof(buf));
        ret = recv(actfd,buf,sizeof(buf),0);
        
        if(0 == ret)
        {
            printf("QT_Client disconnected!\n");
            break;
        }
        if(-1 == ret)
        {
            ERROR("recv");
            close(actfd);
            actfd = -1;
            exit(-1);
        }

        ret = fwrite(buf,1,strlen(buf),fp);
        if(0 == ret)
        {
            ERROR("fwrite");
            exit(-1);
        }
        
    }
    fclose(fp);
    close(actfd);
}

void* sendThreadFunc(void* arg)
{

    int actfd = *(int*)arg;
    free(arg);
    while (1)
    { 
        if (strlen(databuf)>0)
        {
            pthread_mutex_lock(&mutex);

            int ret = send(actfd, databuf, strlen(databuf), 0);
            if (ret <= 0)
            {
                perror("send");
                pthread_mutex_unlock(&mutex);
                break;
            }

            printf("Send to QT successfully: %s\n", databuf);

            memset(databuf, 0, sizeof(databuf));  // 清空
            pthread_mutex_unlock(&mutex);
        }

        usleep(100000);  // 避免占用CPU，100ms
    }

    return NULL;
}